import { getSession } from '@/lib/auth';
import { db } from '@/lib/db';
import { address } from '@/lib/db/schema/common';
import { result } from '@/lib/utils';
import { eq, sql } from 'drizzle-orm';
import { BizError, ErrorCode } from '../error';

export const listAllAddresses = async () => {
  try {
    const session = await getSession();
    if (!session?.user)
      throw new BizError(ErrorCode.Unauthorized, '用户未登录');
    const res = await db.query.address.findMany({
      where: (address, { eq }) => eq(address.userId, session.user.id),
    });
    return result(res);
  } catch (error) {
    return result(error, '获取地址失败');
  }
};

export const checkAddressExist = async () => {
  try {
    const session = await getSession();
    if (!session?.user)
      throw new BizError(ErrorCode.Unauthorized, '用户未登录');
    const res = await db
      .select({
        exists: sql<number>`1`,
      })
      .from(address)
      .where(eq(address.userId, session.user.id));
    return result(res[0]?.exists === 1);
  } catch (error) {
    return result(error, '获取地址失败');
  }
};
